package com.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.CORBA.Request;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.entity.User;
import com.mysql.cj.Session;
import com.service.AdminServiceImpl;

@Controller
public class AdminContrller {
	@Resource
	private AdminServiceImpl adminService;
	
	//管理员登录
	@RequestMapping(value="/admin_login")
	public String login(HttpServletRequest request,HttpServletResponse response ,HttpSession session){
		String name=request.getParameter("name");
		String password=request.getParameter("password");
		String remember=request.getParameter("remember");

		boolean n=this.adminService.AdminByName(name);
		boolean np=this.adminService.AdminByNameAndPwd(name, password, session);

		if(n==false){
			request.setAttribute("noname", "用户名错误");
			return "/admin_login.jsp";
		}else if(np==false){
			request.setAttribute("nopw", "密码错误");
			return "/admin_login.jsp";
		}else {
			if("true".equals(remember) && np==true){
				Cookie cookie=new Cookie("remember", remember);
				cookie.setMaxAge(60*60);
				response.addCookie(cookie);
				Cookie cookie1=new Cookie("name", name);
				cookie.setMaxAge(60*60);
				response.addCookie(cookie1);
				Cookie cookie2=new Cookie("password", password);
				cookie.setMaxAge(60*60);
				session.setAttribute("name", name);
				response.addCookie(cookie2);
				
			}else {
				Cookie[] cookies=request.getCookies();
				if(cookies!=null){
					for(Cookie c:cookies){
						c.setMaxAge(0);
						response.addCookie(c);
					}
				}
			}
			return "/welcome.jsp";
		}
	}
	
	//退出登录
	@RequestMapping("Sgin_out")
	public String outAdmin(HttpServletRequest request){
		HttpSession session=request.getSession();
		session.invalidate();
		return "admin_login.jsp";
		
	}
	@RequestMapping("finduser")
	public String findAllUser(Model model,HttpSession session){
		System.out.println("session:"+session.getAttribute("name"));
		List<User> list=adminService.findAllUser();
		model.addAttribute("list",list);
		return "/finduser.jsp";
		
	}
	@RequestMapping("updataUser/{id}")
	public String findUserById(Model model,@PathVariable int id){
		User user=adminService.findUserById(id);
		model.addAttribute("user",user);
		return "/updatauser.jsp";	
	}
	@RequestMapping(value="updata",produces = "application/json;charset=UTF-8")
	public String updataUser(User u){
		adminService.updateUser(u);
		return "finduser";
		
	}

}
